package com.jbit.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jbit.common.RespBean;
import com.jbit.mapper.UserMapper;
import com.jbit.pojo.User;
import com.jbit.pojo.vo.UserVo;
import com.jbit.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author LiRenZhi
 * @since 2021-08-25
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    /**
     * 分页获取所有用户
     *
     * @return
     */
    @Override
    public RespBean getAllUsers(Integer currentPage, Integer size, UserVo user) {
        Page<User> page = new Page<>(currentPage, size);
        IPage<User> userList = this.baseMapper.getAllUsers(page, getWrapper(user));
        return RespBean.success().data("users", userList.getRecords()).data("total", userList.getTotal());
    }

    /**
     * 封装查询条件
     *
     * @param user
     * @return
     */
    private QueryWrapper<User> getWrapper(UserVo user) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (user != null) {
            if (!StringUtils.isEmpty(user.getDepartmentId())) {
                queryWrapper.eq("department_id", user.getDepartmentId());
            }
            if (!StringUtils.isEmpty(user.getUsername())) {
                queryWrapper.like("username",user.getUsername());
            }
            if (!StringUtils.isEmpty(user.getEmail())) {
                queryWrapper.like("email", user.getEmail());
            }
            if (!StringUtils.isEmpty(user.getSex())) {
                queryWrapper.eq("sex", user.getSex());
            }
            if (!StringUtils.isEmpty(user.getNickname())) {
                queryWrapper.like("nickname", user.getNickname());
            }
        }
        return queryWrapper;
    }
}
